
package com.zhu.salesmanagement.views;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.zhu.salesmanagement.R;
import com.zhu.salesmanagement.StorePhotosActivity;
import com.zhu.salesmanagement.UserLoginActivity;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.PhotoInfoItem;
import com.zhu.salesmanagement.models.ProductInfo;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 门店照片数据
 */
public class StorePhotosView extends LinearLayout implements View.OnClickListener{

    private final static int PHOTOS_QUERY_TOKEN = 0;
    private static final int PICK_FROM_CAMERA = 0;
    private static final int CROP_FROM_CAMERA = 1;

    private final static String TAG = "zhu";
    private boolean isInited = false;
    private LinearLayout mLinearLayout = null;
    private List<PhotoInfoItem> mList = new ArrayList<PhotoInfoItem>();
    private DataQueryHandler mDataQueryHandler = null;
    private StorePhotosActivity mStorePhotosActivity = null;
    private VisitTaskInfo mVisitTaskInfo = null;
    private PhotoInfoItem mTakingItem = null;
    private Uri mImageCaptureUri = null;
    private String[] mValueArray = null;
    private String[] mTypeArray = null;
    private MyLocation mMyLocation = null;
    private Location mCurLocation = null;
    private TextView mTitleView = null;
    private boolean isTakeingPhoto = false;

    public StorePhotosView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public StorePhotosView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onFinishInflate() {
        setupViews();
        super.onFinishInflate();
    }

    /**
     * 初始化界面
     */
    private void setupViews() {
        mLinearLayout = (LinearLayout)findViewById(R.id.sphoto_body);
        findViewById(R.id.input_back).setOnClickListener(this);
        mTitleView = (TextView)findViewById(R.id.input_title);
    }

    /**
     * 初始化数据
     */
    public void initData(StorePhotosActivity activity, VisitTaskInfo visitTaskInfo) {
        mStorePhotosActivity = activity;
        mVisitTaskInfo = visitTaskInfo;
        mTitleView.setText(mVisitTaskInfo.mName);
        mDataQueryHandler = new DataQueryHandler(getContext().getContentResolver());
        mValueArray = getContext().getResources().getStringArray(R.array.photosource_value);
        mTypeArray = getContext().getResources().getStringArray(R.array.photosource_type);
        if (isInited) {
            return;
        }
        isInited = true;
        mList.clear();

        PhotoInfoItem item1 = new PhotoInfoItem();
        item1.iSort = 1;

        PhotoInfoItem item2 = new PhotoInfoItem();
        item2.iSort = 2;

        PhotoInfoItem item3 = new PhotoInfoItem();
        item3.iSort = 3;

        mList.add(item1);
        mList.add(item2);
        mList.add(item3);

        startQuery(mVisitTaskInfo.id);
    }

    /**
     * 获取历史图片数据
     */
    private void startQuery(String cid){
        mDataQueryHandler.startQuery(PHOTOS_QUERY_TOKEN, null, SalesSettings.StorePhotosColumns.CONTENT_URI, 
                null, SalesSettings.StorePhotosColumns.STOREID + " = \'" + cid +"\'", null, SalesSettings.StorePhotosColumns.SORT + " ASC");
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch(v.getId()){
            case R.id.photodataitem_take:
                startTakePhoto((PhotoInfoItem)v.getTag());
                break;
            case R.id.photodataitem_delete:
                deletePhoto((PhotoInfoItem)v.getTag());
                break;
            case R.id.photodataitem_look:
                showBigImage((PhotoInfoItem)v.getTag());
                break;
            case R.id.photodataitem_source:
                popSelectSourceDialog((Button)v);
                break;
            case R.id.input_back:
            	mStorePhotosActivity.finish();
            	break;
        }
    }

    /**
     * 更新界面
     */
    private void updateBody(){
        for(int i = 0 ; i < mList.size(); i++){
            mLinearLayout.addView(getItemView(mList.get(i)));
        }
    }

    /**
     * 获取列表项界面
     * @param item 相片数据
     */
    private View getItemView(PhotoInfoItem item) {
        View view = LayoutInflater.from(this.getContext()).inflate(R.layout.photodata_item, null);
        ImageView preView = (ImageView) view.findViewById(R.id.photodataitem_preview);
        if(item.mBitmap != null){
            preView.setImageBitmap(item.mBitmap);
        }else{
            preView.setImageResource(R.drawable.photo_preview);
        }
        View view1 = view.findViewById(R.id.photodataitem_delete);
        view1.setOnClickListener(this);
        view1.setTag(item);

        view1 = view.findViewById(R.id.photodataitem_look);
        view1.setOnClickListener(this);
        view1.setTag(item);

        view1 = view.findViewById(R.id.photodataitem_take);
        view1.setOnClickListener(this);
        view1.setTag(item);

        Button bn = (Button)view.findViewById(R.id.photodataitem_source);
        int index = this.getSelecledItem(item.mPhotoSource);
        if(index > -1){
            bn.setText(mTypeArray[index]);
        }
        bn.setOnClickListener(this);
        bn.setTag(item);
        item.mButton = bn;
        return view;
    }

    private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case PHOTOS_QUERY_TOKEN:
                    updateCursor(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case PHOTOS_QUERY_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    /**
     * 更新照片数据
     */
    private void updateCursor(Cursor cursor){
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns._ID);
            final int cidIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.STOREID);
            final int dataIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.DATA);
            final int sourceIndex = cursor.getColumnIndexOrThrow(SalesSettings.StorePhotosColumns.PHOTOSOURCE);

            int index = 0;
            while (cursor.moveToNext()) {
                PhotoInfoItem item = mList.get(index);
                item.iDBID = cursor.getLong(idIndex);
                item.mPhotoSource = cursor.getString(sourceIndex);
                byte[] data = cursor.getBlob(dataIndex);
                item.mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                index++;
            }
        }catch(Exception e){

        }finally {
            if(cursor != null){
                cursor.close();
                cursor = null;
            }
        }
        updateBody();
    }

    /**
     * 开始照相
     */
    private void startTakePhoto(PhotoInfoItem item){
    	if (!Actions.isNetwork(getContext())) { //检查网络
            Actions.alertShowDetails(getContext(), getContext().getString(R.string.tips_label),
            		getContext().getString(R.string.network_is_unavailable),
                    R.string.dialog_setting, R.string.dialog_close,
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {
                            Actions.openSettingIntent(getContext(),
                                    Settings.ACTION_WIRELESS_SETTINGS);
                        }
                    }, new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {

                        }
                    });
            return;
        } else if(!Actions.isGPSWorking(getContext())){ //检查GPS
            Actions.alertShowDetails(getContext(), getContext().getString(R.string.tips_label),
            		getContext().getString(R.string.gps_is_unavailable),
                    R.string.dialog_setting, R.string.dialog_close,
                    new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {
                            Actions.openSettingIntent(getContext(),
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        }
                    }, new android.content.DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int arg1) {

                        }
                    });
            return;
        }
    	isTakeingPhoto = true;
        mTakingItem = item;
        startGetLocation();
        doTakePhotoAction();
    }

    /**
     * 处理照相
     */
    private void doTakePhotoAction() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        mImageCaptureUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(),
                            "tmp_contact_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
        try {
            intent.putExtra("return-data", true);
            mStorePhotosActivity.startActivityForResult(intent, PICK_FROM_CAMERA);
        } catch (ActivityNotFoundException e) {
            // Do nothing for now
        }
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (resultCode != StorePhotosActivity.RESULT_OK) {
    		if(mMyLocation != null && mMyLocation.isGetLocationing()){
    			mMyLocation.stop();
    		}
    		isTakeingPhoto = false;
    		return;
    	}
        switch (requestCode) {
            case CROP_FROM_CAMERA:
                final Bundle extras = data.getExtras();
                if (extras != null) {
                    if(mTakingItem.mBitmap != null && !mTakingItem.mBitmap.isRecycled()){
                        mTakingItem.mBitmap.recycle();
                    }
                    Bitmap tem = extras.getParcelable("data");
                    mTakingItem.mBitmap = makeTextBitMap(tem);
                    updateView(mTakingItem);
                }
                isTakeingPhoto = false;
                if(!mMyLocation.isGetLocationing()){
                	if(mTakingItem.iDBID < 0){
                        popSelectSourceDialog(mTakingItem.mButton);
                    }
                    saveData(mTakingItem, false);
                }
                File f = new File(mImageCaptureUri.getPath());
                if (f.exists()) {
                    f.delete();
                }
                break;
            case PICK_FROM_CAMERA: //切图
                Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setDataAndType(mImageCaptureUri, "image/*");
                intent.putExtra("outputX", 320);
                intent.putExtra("outputY", 240);
                intent.putExtra("return-data", true);
                mStorePhotosActivity.startActivityForResult(intent, CROP_FROM_CAMERA);
                break;
        }
    }

    /**
     * 图片加水印
     * @param bitmap 原图
     */
    private Bitmap makeTextBitMap(Bitmap bitmap) {
        Canvas canvasTemp = new Canvas(bitmap);
        canvasTemp.drawColor(Color.TRANSPARENT);
        Paint p = new Paint();
        p.setColor(Color.RED);
        p.setAntiAlias(true);
        p.setTextSize(22);
        canvasTemp.drawText(Util.mVerifyUserResult.name, 0, 170, p);
        canvasTemp.drawText(Util.getFormatTime(), 0, 200, p);
        return bitmap;
    }

    /**
     * 保存数据
     * @param item 数据
     * @param isSaveSource 是否保存图片分类
     */
    private void saveData(PhotoInfoItem item, boolean isSaveSource){
        if(isSaveSource && item.iDBID < 0){
            return;
        }
        ContentValues values = new ContentValues();
        if(!isSaveSource){
        	double lat = 0;
        	double lng = 0;
        	lat = mCurLocation == null ? 0 : mCurLocation.getLatitude();
        	lng = mCurLocation == null ? 0 : mCurLocation.getLongitude();
        	lat = lat == 0 ? Util.mGetGpsLocation.getLastLocation().getLatitude() : lat;
        	lng = lng == 0 ? Util.mGetGpsLocation.getLastLocation().getLongitude() : lng;

            values.put(SalesSettings.StorePhotosColumns.DATA, flattenBitmap(item.mBitmap));
            values.put(SalesSettings.StorePhotosColumns.PHONO_LAT, lat);
            values.put(SalesSettings.StorePhotosColumns.PHOTO_LNG, lng);
            values.put(SalesSettings.StorePhotosColumns.PHONO_TAKETIME, mMyLocation != null ? mMyLocation.getCurrentTime() : System.currentTimeMillis());
        }
        values.put(SalesSettings.StorePhotosColumns.PHOTOSOURCE, item.mPhotoSource);
        
        if(item.iDBID > -1){
            getContext().getContentResolver().update(SalesSettings.StorePhotosColumns.getContentUri(item.iDBID, false), values, null, null);
        }else{
        	if(mVisitTaskInfo.mDatingTaskActualID == null){
                mVisitTaskInfo.mDatingTaskActualID = Util.getDatingTaskActualID(Util.mVerifyUserResult.id, mVisitTaskInfo.id);
            }
        	values.put(SalesSettings.StorePhotosColumns.DTASKACTUALID, mVisitTaskInfo.mDatingTaskActualID);
            values.put(SalesSettings.StorePhotosColumns.STOREID, mVisitTaskInfo.id);
            values.put(SalesSettings.StorePhotosColumns.SORT, item.iSort);
            Uri uri = getContext().getContentResolver().insert(SalesSettings.StorePhotosColumns.CONTENT_URI, values);
            item.iDBID = Long.parseLong(uri.getLastPathSegment());
        }
    }

    private byte[] flattenBitmap(Bitmap bitmap) {
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        ByteArrayOutputStream out = new ByteArrayOutputStream(size);
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            return out.toByteArray();
        } catch (IOException e) {
            return null;
        }
    }

    private void updateView(PhotoInfoItem item){
        View view = mLinearLayout.getChildAt(item.iSort - 1);
        ((ImageView) view.findViewById(R.id.photodataitem_preview)).setImageBitmap(item.mBitmap);
    }

    public void onDestroy(){
        for(int i = 0 ; i < mList.size(); i++){
            PhotoInfoItem item = mList.get(i);
            if(item.mBitmap != null && !item.mBitmap.isRecycled()){
                item.mBitmap.recycle();
                item.mBitmap = null;
            }
        }
    }

    /**
     * 删除照片
     * @param item 删除项
     */
    private void deletePhoto(PhotoInfoItem item){
        if(item.iDBID > -1){
            getContext().getContentResolver().delete(SalesSettings.StorePhotosColumns.getContentUri(item.iDBID, false), null, null);
            item.iDBID = -1;
            if(item.mBitmap != null && !item.mBitmap.isRecycled()){
                item.mBitmap.recycle();
                item.mBitmap = null;
            }
            View view = mLinearLayout.getChildAt(item.iSort - 1);
            ((ImageView) view.findViewById(R.id.photodataitem_preview)).setImageResource(R.drawable.photo_preview);
            item.mButton.setText("");
            item.mPhotoSource="";
            Actions.toastShort(getContext(), getContext().getString(R.string.deletephotosuccess));
        }else{
            Actions.toastShort(getContext(), getContext().getString(R.string.deletephotofail));
        }
    }

    /**
     * 显示大图
     */
    private void showBigImage(PhotoInfoItem item){
        if(item.mBitmap != null){
            ImageView view = new ImageView(getContext());
            view.setImageBitmap(item.mBitmap);
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setView(view);
            builder.create().show();
        }
    }

    private void popSelectSourceDialog(final Button button){
        final PhotoInfoItem info = (PhotoInfoItem)button.getTag();
        int selectedItem = getSelecledItem(info.mPhotoSource);

        new AlertDialog.Builder(getContext())
        .setTitle(R.string.selectfeilei)
        .setCancelable(false)
        .setSingleChoiceItems(mTypeArray, selectedItem,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int which) {
                        button.setText(mTypeArray[which]);
                        dialog.dismiss();
                        info.mPhotoSource = mValueArray[which];
                        saveData(info, true);
                    }
                }).show();
    }

    private int getSelecledItem(String value) {
        if (value == null || value.trim().length() == 0 || value.equals("default")) {
            return -1;
        } else {
            for (int i = 0; i < mValueArray.length; i++) {
                if (mValueArray[i].equals(value)) {
                    return i;
                }
            }
        }
        return -1;
    }

    
    private void startGetLocation(){
        if(mMyLocation == null){
            mMyLocation = new MyLocation(this.getContext(), true, false);
        }
        mMyLocation.getLocation(locationResult, true);
    }

    /**
     * 定位结果
     */
    public LocationResult locationResult = new LocationResult() {
        public void gotLocation(final Location location) {
        	mCurLocation = location;
        	if(!isTakeingPhoto){
        		if(mTakingItem.iDBID < 0){
                    popSelectSourceDialog(mTakingItem.mButton);
                }
                saveData(mTakingItem, false);
        	}
        }
    };
}
